package com.myx.zookeeper.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class MointorController {

   @Value("${mointor.zk.nodes}")
   private String nodes;


   /**
    * mointor/config
    * @param model
    * @param command
    * @return
    */
   @RequestMapping("/mointor/{command}")
   public String list(Map<String, Object> model, @PathVariable String command){
      try {
         List<Map<String,String>> zkList =new ArrayList<>();
         //拆分uri
         String[] nodesList=nodes.split(",");
         for (int i = 0; i < nodesList.length; i++) {
            Map<String,String> map =new HashMap<>();
            String[] split = nodesList[i].split(":");
            model.put("zk"+(i+1),hander(command,split[0],split[1]));
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
      return  "mointer";
   }


   /**
    * 处理
    * @param command
    * @param ip
    * @param port
    * @return
    * @throws IOException
    */
   public String hander(String command,String ip,String port) throws IOException {
      Socket socket=new Socket(ip,Integer.parseInt(port));
      OutputStream outputStream=socket.getOutputStream();
      outputStream.write(command.getBytes());
      outputStream.flush();
      return IOUtils.toString(socket.getInputStream());
   }

}
